const Router = require('koa-router')
const jwt = require('../middlewares/jwt.middleware')
const isRole = require('../middlewares/role.middleware')
const config = require('../../config.json')
const fs = require('fs')
const path = require('path')

const router = new Router()
router.prefix('/api/config')

router.get('/', jwt, ctx => ctx.response.body = config)

router.put('/', jwt, isRole(['admin']), async ctx => {
  const body = ctx.request.body
  Object.assign(config, body)
  await fs.promises.writeFile(path.join(__dirname, '../../config.json'), JSON.stringify(config), 'utf-8')
  ctx.response.body = config
})

module.exports = router